
package com.azt.back.action.user;

import com.alibaba.fastjson.JSONArray;
import com.azt.api.enums.CompanyIdentityEnum;
import com.azt.api.enums.RoleTypeEnum;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.back.action.BaseAction;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;
import com.xiaoleilu.hutool.convert.Convert;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/company")
public class CompanyAction extends BaseAction {

	@Autowired
	private CompanyService companyservice;

	@Autowired
	private AreaService areaService;

	@Autowired
	private CompanySignService companysignservice;

	@Autowired
	private SignApplyService signapplyservice;

	@Autowired
	private ProCategoryService proCagoryService;

	@Autowired
	private AreaService as;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private UserService userService;

	@Autowired
	private MemberApplyService memberApplyService;

	@Autowired
	private PinganAccountService pinganAccountService;

	/**
	 * 分页条件查询企业
	 * 
	 * @param request
	 * @param pageNo
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/company_list.do")
	public String customerList(HttpServletRequest request, Integer pageNo, HttpServletResponse response,
			ModelMap model) {
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		Pagination pagination = companyservice.getCompanyPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE,
				searchMap);
		model.put("pagination", pagination);
		model.put("categorys", proCagoryService.queryFathCategorys());
		RequestUtils.MapToModelMap(searchMap, request);
		return "company/company_list";
	}

	/**
	 * 导出企业excel
	 * 
	 * @param request
	 * @param response
	 * @param ind
	 * @param ids
	 */
	@RequestMapping("/imporetComToExcel.do")
	public void imporetComToExcel(HttpServletRequest request, HttpServletResponse response, String ind, String ids) {
		List<Map<String, String>> companys = companyservice.selectExportCompany(ids);
		try {
			String title = "公司详情";
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(title);
			sheet.autoSizeColumn(1);
			HSSFRow row = sheet.createRow(0);
			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			HSSFCell cell = row.createCell(0);
			String[] titles = { "公司名称", "注册详细地址", "经营详细地址", "税号", "公司营业执照地址", "注册法人" };
			for (int i = 0; i < titles.length; i++) {
				cell.setCellValue(titles[i]);
				cell.setCellStyle(style);
				cell = row.createCell(i + 1);
			}
			String[] fields = { "companyName", "regAddress", "businessAddress", "taxNumber", "businessLicense",
					"legalperson" };
			for (int i = 0; i < companys.size(); i++) {
				row = sheet.createRow(i + 1);
				for (int j = 0; j < titles.length; j++) {
					cell = row.createCell(j);
					cell.setCellValue(
							companys.get(i).get(fields[j]) == null ? "" : companys.get(i).get(fields[j]).toString());
				}
			}

			title = title + ".xls";
			title = new String(title.getBytes("UTF-8"), "iso8859-1");

			response.setContentType("application/vnd.ms-excel;");
			response.setHeader("Content-Disposition", "attachment;filename=" + title);

			ServletOutputStream outputStream = response.getOutputStream();
			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 进入企业编辑页
	 * 
	 * @param comid
	 * @param model
	 * @return
	 */
	@RequestMapping("/showComDetails.do")
	public String showComdetails(String comid, Model model) {
		Company company = companyservice.showComDetails(comid);
		if(company!=null){
			Company topcompany = companyservice.getTopParentCompany(company.getId());
			model.addAttribute("topcompany", topcompany);
		}
		model.addAttribute("company", company);
		model.addAttribute("companyinfo", company.getCompanyInfo());
		model.addAttribute("chinasheng", as.findChinaAreas());
		model.addAttribute("procates", proCagoryService.queryFathCategorys());
		model.addAttribute("applifies", dictionaryService.getDictionByParentCode("applifield"));
		model.addAttribute("account", pinganAccountService.getValidAccountByCompanyId(company.getId()));
		return "company/company_edit";
	}

	/**
	 * @description 自动完成所有公司的查询 可公用 参数：query查询字符串 matchCount 返回数量
	 * @return
	 * @author 查恒 2016年8月8日上午9:55:58
	 */
	@ResponseBody
	@RequestMapping("/autocustomer.do")
	public AjaxJson autoCustomer(String query, Integer matchCount) {
		AjaxJson json = new AjaxJson();
		List findCompanyByQuery = companyservice.findCompanyByQuery(query, matchCount);
		JSONArray j = (JSONArray) JSONArray.toJSON(findCompanyByQuery);
		json.setObj(j);
		return json;
	}

	@ResponseBody
	@RequestMapping("query.do")
	public AjaxJson query(@RequestParam(value = "q", required = false) String q,
						  @RequestParam(value = "page", defaultValue = "1") Integer page) {
		Map<String, Object> params = new HashMap<>();
		params.put("companyName", q);
		Pagination pagin = companyservice.listCompany(page, Globals.PAGE_SIZE, params);
		return AjaxJson.success().setObj(pagin);
	}

	/**
	 * 修改企业审核通过状态
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/ajax_audit.do")
	public AjaxJson changeCompanyState(String id) {
		return companyservice.changeCompanyState(id, ContextUtils.getAdmin().getId());
	}

	/**
	 * @Title: delCompany
	 * @Description: 删除公司 1.有分公司的不能删除 2.删除公司后见那个公司removed设置为1，公司名称前缀加（已删除）
	 *               3.删除后公司下面的员工公司全部解绑，角色设置为注册用户。
	 * @param id
	 * @param auditOpinion
	 * @return
	 * @return: AjaxJson
	 * @author: 查恒 2017年3月27日 下午5:30:20
	 */
	@ResponseBody
	@RequestMapping("/ajax_delCompany.do")
	public AjaxJson delCompany(Integer id) {
		AjaxJson json = new AjaxJson();
		if (id != null) {
			Company company = companyservice.getCompanyById(id);
			if (company != null) {
				List<Company> branchCompanys = companyservice.getBranchCompany(company.getId());
				if (branchCompanys != null && branchCompanys.size() > 0) {
					json.setMsg("该公司下有分公司，不可删除！");
					json.setSuccess(false);
				} else {
                //可删除
					try {
						companyservice.delCompany(company);
						json.setSuccess(true);
					} catch (Exception e) {
						json.setMsg("删除失败");
						json.setSuccess(false);
						return json;
					}
					
				}
			}else{
				json.setMsg("删除失败，该公司不存在或已删除！");
				json.setSuccess(false);
			}
		} else {
			json.setMsg("删除失败，记录不存在！");
			json.setSuccess(false);
		}

		return json;
	}

	/**
	 * 修改企业退回修改状态
	 * 
	 * @Title: changeSendBackCompany
	 * @Description: TODO
	 * @param id
	 * @return
	 * @return: AjaxJson
	 * @author: zhoudongdong 2016年9月5日 上午11:13:26
	 */
	@ResponseBody
	@RequestMapping("/ajax_sendback.do")
	public AjaxJson changeSendBackCompany(String id, String auditOpinion) {
		return companyservice.changeSendBackCompanyState(id, auditOpinion);
	}

	@RequestMapping("/company_edit.do")
	public String doEditCompany(Company company, HttpServletRequest request) {
		companyservice.editcompany(company);
		return "redirect:/company/showComDetails.do?comid=" + company.getId();
	}

	@ResponseBody
	@RequestMapping(value = "/company_editField.do", method = RequestMethod.POST)
	public AjaxJson doEditCompanyField(@RequestBody Company companymain) {
		try {
			companyservice.editcompany(companymain);
			return AjaxJson.success("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxJson.error("系统繁忙");
		}
	}

	@ResponseBody
	@RequestMapping("/querycityBycodeNew.do")
	public List<Area> querycityBycodeNew(String code, String id) {
		if (StringUtils.isNoneBlank(code)) {
			return as.getAreaByParentCode(code);
		} else if (StringUtils.isNoneBlank(id)) {
			return as.getAreaByParentId(Integer.parseInt(id));
		}
		return null;
	}

	@RequestMapping("/companysign_list.do")
	public String getCompanySign(HttpServletRequest request, Integer pageNo, HttpServletResponse response,
			ModelMap model) {
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		Pagination pagination = companysignservice.getCompanySignPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE,
				searchMap);
		model.put("pagination", pagination);
		model.addAttribute("identitys", dictionaryService.getDictionByParentCode("cpIdentity"));
		model.addAttribute("identityMap", CommonUtil.getEnumMap(CompanyIdentityEnum.class));
		RequestUtils.MapToModelMap(searchMap, request);
		return "companysign/companysign_list";
	}

	@ResponseBody
	@RequestMapping(value = "/companysign_disable.do", method = RequestMethod.POST)
	public AjaxJson disable(int id) {
		CompanySign companySign = companysignservice.getById(id);
		if (null != companySign) {
			companySign.setUsable(0);
			companysignservice.edit(companySign);
		}
		return AjaxJson.success("设置失效成功");
	}

	@RequestMapping("/companysign_detail.do")
	public String goDetail(HttpServletRequest request, HttpServletResponse response, ModelMap model, int id,
			String totalPrice) {
		CompanySign companySign = companysignservice.getById(id);
		String companyid = companySign.getCompanyId().toString();
		Company company = companyservice.showComDetails(companyid);
		companySign.setTotalPrice(totalPrice);
		model.put("companySign", companySign);
		model.put("company", company);
		model.addAttribute("identityMap", CommonUtil.getEnumMap(CompanyIdentityEnum.class));
		return "companysign/companysign_detail";
	}

	@RequestMapping(value = "/companysign_v_add.do")
	public String addContract(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		model.addAttribute("identityMap", CommonUtil.getEnumMap(CompanyIdentityEnum.class));
		return "companysign/companysign_add";
	}

	/**
	 * 检查公司是否能签约，能的话则返回公司的资质信息
	 */
	@ResponseBody
	@RequestMapping(value = "/checkCompanySign.do", method = RequestMethod.POST)
	public AjaxJson checkCompanySign(String id, ModelMap model) {
		if (companysignservice.getCompanySign(Convert.toInt(id), 2, true) == null) {
			Company company = companyservice.showComDetails(id);
			List<CompanyAsset> list = company.getCompanyAssets();
			return AjaxJson.success().setObj(list);
		} else {
			return AjaxJson.error("该公司已经签约过了，不能重复签约");
		}
	}

	@RequestMapping(value = "/companysign_o_add.do")
	public String addCompanySign(CompanySign companysign) {
		companysignservice.signCompany(companysign, ContextUtils.getAdmin().getId());
		return "redirect:/company/companysign_list.do";
	}

	@RequestMapping("/signapply_list.do")
	public String getSignApply(HttpServletRequest request, Integer pageNo, HttpServletResponse response,
			ModelMap model) {
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		Pagination pagination = signapplyservice.getSignApplyPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE,
				searchMap);
		model.put("pagination", pagination);
		model.addAttribute("identityMap", CommonUtil.getEnumMap(CompanyIdentityEnum.class));
		RequestUtils.MapToModelMap(searchMap, request);
		return "signapply/signapply_list";
	}

	@ResponseBody
	@RequestMapping("remark.do")
	public AjaxJson remark(@RequestParam("id") Integer id, @RequestParam("auditOpinion") String auditOpinion) {
		signapplyservice.updateAudioOption(id, auditOpinion);
		return AjaxJson.success();
	}

	@RequestMapping("/exportSignApplyExcel.do")
	public void exportSignApplyExcel(HttpServletRequest request, HttpServletResponse response, String ind, String ids) {
		List<SignApply> signs = signapplyservice.querySignListByIds(ids);
		try {
			String title = "合作服务商";
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(title);
			sheet.autoSizeColumn(1);
			HSSFRow row = sheet.createRow(0);
			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			HSSFCell cell = row.createCell(0);
			String[] titles = { "公司名称", "联系人", "联系电话", "申请身份" };
			for (int i = 0; i < titles.length; i++) {
				cell.setCellValue(titles[i]);
				cell.setCellStyle(style);
				cell = row.createCell(i + 1);
			}
			for (int i = 0; i < signs.size(); i++) {
				row = sheet.createRow(i + 1);
				row.createCell(0).setCellValue(signs.get(i).getCompanyName());
				row.createCell(1).setCellValue(signs.get(i).getContacter());
				row.createCell(2).setCellValue(signs.get(i).getPhone());
				row.createCell(3).setCellValue(signs.get(i).getIdentity());
			}

			title = title + ".xls";
			title = new String(title.getBytes("UTF-8"), "iso8859-1");

			response.setContentType("application/vnd.ms-excel;");
			response.setHeader("Content-Disposition", "attachment;filename=" + title);

			ServletOutputStream outputStream = response.getOutputStream();
			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/memberapply_list.do")
	public String getMemberApply(HttpServletRequest request, Integer pageNo, HttpServletResponse response,
			ModelMap model) {
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		Pagination pagination = memberApplyService.getMemberApplyPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE,
				searchMap);
		model.put("pagination", pagination);
		RequestUtils.MapToModelMap(searchMap, request);
		return "memberapply/memberapply_list";
	}

	@RequestMapping("/insertDesc.do")
	@ResponseBody
	public AjaxJson insertDesc(MemberApply memberApply) {
		AjaxJson aj = new AjaxJson();
		try {
			memberApplyService.update(memberApply);
		} catch (Exception e) {
			aj = AjaxJson.error("系统出错");
			e.printStackTrace();
		}
		return aj;
	}

	@RequestMapping("/exportMemberApplyExcel.do")
	public void exportMemberApplyExcel(HttpServletRequest request, HttpServletResponse response, String ind,
			String ids) {
		List<MemberApply> applys = memberApplyService.queryListByIds(ids);
		 try {
		 	String title="大单采集申请表";
	        HSSFWorkbook wb = new HSSFWorkbook();  
	        HSSFSheet sheet = wb.createSheet(title);  
	        sheet.autoSizeColumn(1);
	        HSSFRow row = sheet.createRow(0);
	        HSSFCellStyle style = wb.createCellStyle();  
	        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	        HSSFCell cell = row.createCell(0);
	        String[] titles={"公司名称","联系人","联系电话","经营品牌","合作意向","备注内容"};
	        for (int i = 0; i < titles.length; i++) {
				cell.setCellValue(titles[i]);
				cell.setCellStyle(style);
				cell = row.createCell(i + 1);
			}
	        for (int i = 0; i < applys.size(); i++) {
	        	 row = sheet.createRow(i+1);
	        	 row.createCell(0).setCellValue(applys.get(i).getCompanyName());
	        	 row.createCell(1).setCellValue(applys.get(i).getContacts());
	        	 row.createCell(2).setCellValue(applys.get(i).getTel());
	        	 row.createCell(3).setCellValue(applys.get(i).getBrands());
	        	 row.createCell(4).setCellValue(applys.get(i).getCoopIntention());
				 row.createCell(5).setCellValue(applys.get(i).getAuditOpinion());
			}

			title = title + ".xls";
			title = new String(title.getBytes("UTF-8"), "iso8859-1");

			response.setContentType("application/vnd.ms-excel;");
			response.setHeader("Content-Disposition", "attachment;filename=" + title);

			ServletOutputStream outputStream = response.getOutputStream();
			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/companyUserList.do")
	public String companyUserList(HttpServletRequest request, Integer pageNo, HttpServletResponse response,
			ModelMap model) {
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		Pagination pagination = userService.getFrontUserPageByCid(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE,
				searchMap);
		pagination.setParams(searchMap);
		model.put("pagination", pagination);

		Integer companyId = getParaToInt("so_companyId");
		Company company = companyservice.getCompanyById(companyId);
		Integer roleType = null;
		if (company.getIspurchaser().intValue() == 1) {
			// 采购商
			roleType = RoleTypeEnum.PURCHASER.getValue();
		} else {
			// 供应商
			roleType = RoleTypeEnum.PROVIDER.getValue();
		}

		List<Role> roleList = userService.findRoleByCompanyId(company, roleType);
		model.put("roleList", roleList);
		RequestUtils.MapToModelMap(searchMap, request);
		return "company/company_user_roles";
	}

	@RequestMapping("/ajax_editrole.do")
	@ResponseBody
	public AjaxJson doEditUserRole(Integer roleType, Integer userId, Integer orRoleId) {
		AjaxJson aj = new AjaxJson();
		try {
			userService.changeRoleByUserId(userId, roleType, orRoleId);
			aj = AjaxJson.success("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			aj = AjaxJson.error("修改失败");
		}
		return aj;
	}

	@RequestMapping("/ajax_forbidden.do")
	@ResponseBody
	public AjaxJson forbiddenUser(Integer userId, Integer state) {
		AjaxJson aj = new AjaxJson();
		try {
			userService.forbiddenUser(userId, state);
		} catch (Exception e) {
			e.printStackTrace();
			aj = AjaxJson.error("操作失败");
		}
		return aj;
	}

	/**
	 * @Description 省市区查询
	 * @param code
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/querycityBycode.do")
	public List<Area> querycityBycode(String code, String id) {
		if (StringUtils.isNoneBlank(code)) {
			return areaService.getAreaByParentCode(code);
		} else if (StringUtils.isNoneBlank(id)) {
			return areaService.getAreaByParentId(Integer.parseInt(id));
		}
		return null;
	}

	/**
	 * 同意审核，设置状态为1
	 */
	@RequestMapping("/auditSign.do")
	@ResponseBody
	public AjaxJson istrueAjax(HttpServletRequest request, HttpServletResponse response, SignApply apply) {
		AjaxJson aj = new AjaxJson();
		apply.setAuditState(1);
		signapplyservice.SaveOrUpdateapply(apply);
		return aj;
	}

	/**
	 * 不同意审核，状态为2
	 * 
	 * @Title: isfalseAjax
	 * @Description: TODO
	 * @param request
	 * @param response
	 * @param apply
	 * @return
	 * @return: AjaxJson
	 * @author: 叶青 2017年2月27日 下午6:43:49
	 */
	@RequestMapping("/auditSign1.do")
	@ResponseBody
	public AjaxJson isfalseAjax(HttpServletRequest request, HttpServletResponse response, SignApply apply) {
		AjaxJson aj = new AjaxJson();
		apply.setAuditState(2);
		signapplyservice.SaveOrUpdateapply(apply);
		return aj;
	}

}
